package com.skyolder.milkbee.web.rest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Optional;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.skyolder.milkbee.domain.User;
import com.skyolder.milkbee.dto.UploadResult;
import com.skyolder.milkbee.dto.UploadState;
import com.skyolder.milkbee.security.SecurityUtils;
import com.skyolder.milkbee.service.UserService;
import com.skyolder.milkbee.tool.FileUtil;
import com.skyolder.milkbee.tool.ImageUtil;

@RestController
@RequestMapping("/upload")
public class FileUploader {
	/**
	 * 图片目录
	 */
	public static final String PICTUREDIR = "/content/images/upload/picture/";
	/**
	 * 实名身份证目录
	 */
	public static final String IDPICTURE = "/content/images/upload/idpicture/";
	/**
	 * 真实照片
	 */
	public static final String REALPICTURE = "/content/images/upload/realpicture/";
	/**
	 * 头像
	 */
	public static final String AVATAR = "/content/images/upload/avatar/";
	/**
	 * 附件目录
	 */
	public static final String ATTACHMENT = "/content/images/upload/attachment/";

	public static final String LOGO = "/content/images/";

	public static final String GIFT = "/content/images/upload/gift/";
	public static final String AWARD = "/content/images/upload/award/";
	public static final String ADVERTISEMENT = "/content/images/upload/advertisement/";
	public static final String CATEGORYLOGO = "/content/images/upload/category/";

	@Inject
	private UserService userService;

	@PostMapping("/picture")
	public ResponseEntity<UploadResult> uploadPicture(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(PICTUREDIR);
		String filename = new Date().getTime() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/idpicture")
	public ResponseEntity<UploadResult> uploadPhoto(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(IDPICTURE);
		String filename = new Date().getTime() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/realpicture")
	public ResponseEntity<UploadResult> uploadRealpicture(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(REALPICTURE);
		String filename = new Date().getTime() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/avatar")
	public ResponseEntity<UploadResult> uploadAvatar(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(AVATAR);
		// String filename = new Date().getTime() + ".jpg";
		Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
		User user = ouser.get();
		String filename = "" + user.getId() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		try {
			ImageUtil.thumbAvatar(realpath + "/" + filename);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/attachment")
	public ResponseEntity<UploadResult> uploadAttachment(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(ATTACHMENT);
		String filename = new Date().getTime() + ".zip";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/logo")
	public ResponseEntity<UploadResult> uploadLogo(@RequestParam(value = "jyfile", required = false) MultipartFile file,
			HttpServletRequest request) throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(LOGO);
		boolean b = upload(realpath + "/" + "logo.png", file);
		UploadResult ur = new UploadResult();
		ur.setPath("logo.png");
		ur.setUrl("logo.png");
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		/*
		 * try { ImageUtil.thumbLogo(realpath + "/" + "logo.png"); } catch
		 * (IOException e) { e.printStackTrace(); }
		 */
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/gift")
	public ResponseEntity<UploadResult> uploadGift(@RequestParam(value = "jyfile", required = false) MultipartFile file,
			HttpServletRequest request) throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(GIFT);
		String filename = new Date().getTime() + ".gif";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/award")
	public ResponseEntity<UploadResult> uploadAward(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(AWARD);
		String filename = new Date().getTime() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/advertisement")
	public ResponseEntity<UploadResult> uploadAdvertisement(
			@RequestParam(value = "jyfile", required = false) MultipartFile file, HttpServletRequest request)
			throws URISyntaxException {
		String realpath = request.getSession().getServletContext().getRealPath(ADVERTISEMENT);
		String filename = new Date().getTime() + ".jpg";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	@PostMapping("/category/{categoryId}")
	public ResponseEntity<UploadResult> uploadCategoryLogo(
			@RequestParam(value = "jyfile", required = false) MultipartFile file,@PathVariable Long categoryId) throws URISyntaxException {
		String realpath = FileUtil.getWebRealPath(CATEGORYLOGO);
		String filename = categoryId + ".png";
		boolean b = upload(realpath + "/" + filename, file);
		UploadResult ur = new UploadResult();
		ur.setPath(filename);
		ur.setUrl(filename);
		ur.setSuccess(b);
		ur.setSize(file.getSize());
		ur.setState(UploadState.SUCCESS);
		return new ResponseEntity<>(ur, HttpStatus.OK);
	}

	private boolean upload(String path, MultipartFile file) {
		try {
			File localFile = new File(path);
			if (!localFile.getParentFile().exists()) {
				// 分两次mkdirs，是为了避免目录层级过高导致目录创建失败的情况
				localFile.getParentFile().mkdirs();
			}
			if (localFile.exists()) {
				localFile.delete();
			}
			localFile.createNewFile();
			// 获取输出流
			OutputStream os = new FileOutputStream(localFile);
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			InputStream is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
			os.close();
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;

	}
}
